package com.diaohw.platform.common.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

public class LocalDateTimeUtil extends cn.hutool.core.date.LocalDateTimeUtil {

    /**
     * 时间交集
     */
    public static LocalDateTime[] intersection(LocalDateTime start1, LocalDateTime end1, LocalDateTime start2, LocalDateTime end2) {
        if (start1.isAfter(end1) || start2.isAfter(end2) || start1.isAfter(end2) || start2.isAfter(end1)) {
            return new LocalDateTime[0];
        }

        LocalDateTime start = start1.isBefore(start2) ? start2 : start1;
        LocalDateTime end = end1.isAfter(end2) ? end2 : end1;

        return new LocalDateTime[]{start, end};
    }

    /**
     * 时间交集
     */
    public static LocalDate[] intersection(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
        if (start1.isAfter(end1) || start2.isAfter(end2) || start1.isAfter(end2) || start2.isAfter(end1)) {
            return new LocalDate[0];
        }

        LocalDate start = start1.isBefore(start2) ? start2 : start1;
        LocalDate end = end1.isAfter(end2) ? end2 : end1;

        return new LocalDate[]{start, end};
    }

    /**
     * 时间交集
     */
    public static LocalTime[] intersection(LocalTime start1, LocalTime end1, LocalTime start2, LocalTime end2) {
        if (start1.isAfter(end1) || start2.isAfter(end2) || start1.isAfter(end2) || start2.isAfter(end1)) {
            return new LocalTime[0];
        }

        LocalTime start = start1.isBefore(start2) ? start2 : start1;
        LocalTime end = end1.isAfter(end2) ? end2 : end1;

        return new LocalTime[]{start, end};
    }

    /**
     * 按照秒切割时间区间
     */
    public static List<LocalDateTime[]> splitBySecond(LocalDateTime startTime, LocalDateTime endTime, int seconds) {
        if (endTime.isBefore(startTime)) {
            return List.of();
        }
        List<LocalDateTime[]> dateSplits = new ArrayList<>();
        LocalDateTime temStart = startTime;
        while (true) {
            LocalDateTime tempEndTime = temStart.plusSeconds(seconds - 1);
            if (tempEndTime.isAfter(endTime)) {
                tempEndTime = endTime;
            }

            LocalDateTime[] times = {temStart, tempEndTime};
            dateSplits.add(times);

            temStart = temStart.plusSeconds(seconds);
            if (temStart.isAfter(endTime) || tempEndTime.isAfter(endTime) || temStart.isEqual(endTime)) {
                times[1] = endTime;
                break;
            }
        }
        return dateSplits;
    }

    public static int year() {
        return LocalDate.now().getYear();
    }

    public static int month() {
        return LocalDate.now().getMonthValue();
    }

    public static int day() {
        return LocalDate.now().getDayOfMonth();
    }

}
